import type { Ref } from "vue";

type UseStateReturnType<T> = [
    Ref<T>, // 状态值
    (value: T) => void, // 设置状态值
    () => void, // 重置状态值
]

export const useState = <T>(defaultValue: T | (() => T)): UseStateReturnType<T> => {
  const getState = () => {
    return typeof defaultValue === 'function' ? (defaultValue as () => T)() : defaultValue;
  }

  const state = ref(getState()) as Ref<T>;
  return [
    state,
    (value: T) => {
      state.value = value;
    },
    () => (state.value = getState()),
  ];
};

